import { getTokenAsync } from './secure-storage';
import { API_BASE_URL } from '@/config/env';

export interface ImSingleMessage {
  message_id: string;
  from_id: string;
  to_id: string;
  message_body: string;
  message_time: number;
  message_content_type: number;
  read_status: number;
  extra?: string;
  del_flag: number;
  sequence: number;
  message_random?: string;
  create_time?: number;
  update_time?: number;
  version?: number;
  reply_to?: string;
}

export interface ImGroupMessage {
  message_id: string;
  group_id: string;
  from_id: string;
  message_body: string;
  message_time: number;
  message_content_type: number;
  extra?: string;
  del_flag: number;
  sequence?: number;
  message_random?: string;
  create_time: number;
  update_time?: number;
  version?: number;
  reply_to?: string;
}

export interface SendSingleMessageRequest {
  from_id: string;
  to_id: string;
  message_body: string;
  message_content_type: number;
  extra?: string;
  reply_to?: string;
}

export interface SendGroupMessageRequest {
  group_id: string;
  from_id: string;
  message_body: string;
  message_content_type: number;
  extra?: string;
  reply_to?: string;
}

export const sendSingleMessage = async (req: SendSingleMessageRequest): Promise<void> => {
  const token = localStorage.getItem('token');
  
  // 确保所有ID都是字符串格式
  const requestBody = {
    from_id: String(req.from_id),
    to_id: String(req.to_id),
    message_body: String(req.message_body),
    message_content_type: req.message_content_type,
    extra: req.extra,
    reply_to: req.reply_to,
  };
  
  console.log('发送单聊消息请求:', requestBody);
  
  const response = await fetch(`${API_BASE_URL}/api/im/messages/single`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestBody),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '发送消息失败' }));
    console.error('发送消息失败:', {
      status: response.status,
      statusText: response.statusText,
      error: error,
      request: requestBody,
    });
    throw new Error(error.message || `发送消息失败 (${response.status})`);
  }
};

export const getSingleMessages = async (
  to_id: string,
  since_sequence?: number,
  limit: number = 100
): Promise<ImSingleMessage[]> => {
  const token = localStorage.getItem('token');
  const params = new URLSearchParams();
  params.append('to_id', to_id);
  if (since_sequence !== undefined) {
    params.append('since_sequence', since_sequence.toString());
  }
  params.append('limit', limit.toString());

  const response = await fetch(`${API_BASE_URL}/api/im/messages/single?${params.toString()}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取消息失败' }));
    throw new Error(error.message || '获取消息失败');
  }

  const data = await response.json();
  return data.messages || [];
};

export const markSingleMessageRead = async (message_id: string): Promise<void> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/im/messages/single/${encodeURIComponent(message_id)}/read`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '标记消息已读失败' }));
    throw new Error(error.message || '标记消息已读失败');
  }
};

export const sendGroupMessage = async (req: SendGroupMessageRequest): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(`${API_BASE_URL}/api/im/messages/group`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '发送群消息失败' }));
    throw new Error(error.message || '发送群消息失败');
  }
};

export const getGroupMessages = async (
  group_id: string,
  since_sequence?: number,
  limit: number = 100
): Promise<ImGroupMessage[]> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const params = new URLSearchParams();
  if (since_sequence !== undefined) {
    params.append('since_sequence', since_sequence.toString());
  }
  params.append('limit', limit.toString());

  const response = await fetch(`${API_BASE_URL}/api/im/messages/group/${encodeURIComponent(group_id)}?${params.toString()}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取群消息失败' }));
    throw new Error(error.message || '获取群消息失败');
  }

  const data = await response.json();
  return data.messages || [];
};

export const markGroupMessageRead = async (group_id: string, message_id: string): Promise<void> => {
  const token = await getTokenAsync();
  if (!token) {
    throw new Error('未登录，请先登录');
  }
  const response = await fetch(
    `${API_BASE_URL}/api/im/messages/group/${encodeURIComponent(group_id)}/${encodeURIComponent(message_id)}/read`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    }
  );

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '标记群消息已读失败' }));
    throw new Error(error.message || '标记群消息已读失败');
  }
};

